<?php
//基础的控制器类
namespace app\api\controller;

use think\Controller;


class BaseApi extends Controller
{

    private $_iv = 'q3d4f5c6hb3fd78l';
    private $_secret = '5tgf4d7d3ak9gvf4';

    //初始化方法
    public function _initialize()
    {
        parent::_initialize();
        // 允许的源域名  全部允许访问
        header("Access-Control-Allow-Origin: *");

        // 允许本机访问
        // header("Access-Control-Allow-Origin: http://192.168.1.112:8080");
        // header("Access-Control-Allow-Origin: http://192.168.1.112:3306");
        // header("Access-Control-Allow-Origin:  http://172.20.10.4:8080");

        // header("Access-Control-Allow-Origin: http://39.107.236.5");
        // header("Access-Control-Allow-Origin: https://39.107.236.5");


        //允许的请求头信息
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); //允许的请求类型
        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
    }

    /**
     * 通用响应
     * @param int $code 错误码
     * @param string $msg 错误描述 * @param array $data 返回数据 */
    public function response($code = 1000, $msg = 'success', $data = [])
    {
        $res = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        //以下两行二选一
        //echo json_encode($res, JSON_UNESCAPED_UNICODE);die;
        json($res)->send();
        die;
    }


    /**
     * 失败时响应
     * @param string $msg 错误描述 * @param int $code 错误码
     */
    public function fail($msg = 'fail', $code = 404)
    {
        return $this->response($code, $msg);
    }

    /* 成功时响应
    * @param array $data 返回数据 * @param int $code 错误码
    * @param string $msg 错误描述 */
    public function ok($data = [], $code = 1000, $msg = 'success')
    {
        return $this->response($code, $msg, $data);
    }


    public function aes_encrypt($data)
    {
        # code...
        //  $data = base64_encode($data);
        $str =  openssl_encrypt($data, 'aes-128-cbc', $this->_secret, false, $this->_iv);
        // $str = base64_encode($str);
        return $str;
    }
    public function aes_deencrypt($secretData)
    {
        # code...
        $res =  openssl_decrypt($secretData,'aes-128-cbc',$this->_secret,false,$this->_iv);
        return $res;
    } 
}
